<?php

namespace polymerize\auth\module\login;


use app\common\InstanceTrait;
use app\common\LoginType;
use app\model\User as UserModel;
use app\model\UserBehaviorLog;
use app\model\UserToken;
use app\service\WeiboService;

class WeiboLogin
{
    use InstanceTrait;

    /**
     * 微博登录
     *
     * @param string $token
     * @param int    $weiboUid
     * @param string $ref
     * @param int    $bindUid
     * @return array
     */
    public function weiboLogin(string $token, int $weiboUid, string $ref, int $bindUid): array
    {
        if ($bindUid) {
            $where1[] = ['id', '=', $bindUid];
            $user     = UserModel::where($where1)->find();
            if (!$user) return ['code' => 400, 'msg' => '绑定用户信息不存在'];
        }
        try {
            $user = WeiboService::instance()->_weibo_login_callback($token, $weiboUid, $ref, $bindUid);
            if ($user['code'] != 200) return ['code' => 400, 'msg' => $user['msg']];
            $user = $user['data'];

            $user_status = true;
            if ($user['status'] != 1) $user_status = false;
            $param = [
                'uid'         => $user['id'],
                'type'        => 2,
                'user_status' => $user_status ? 1 : 2,
                'status'      => $user_status ? 1 : 2,
                'login_type'  => LoginType::LOGIN_TYPE_WEIBO->value
            ];
            UserBehaviorLog::log($param);
            if (!$user_status) return ['code' => 400, 'msg' => '当前账号状态异常，请联系管理员'];

            $token         = UserToken::loginToken($user, LoginType::LOGIN_TYPE_WEIBO->value);
            $data['token'] = $token['token'] ?? '';

            $uid         = $user['id'];
            $data['uid'] = $uid;

            return ['code' => 200, 'msg' => '登录成功', 'data' => $data];
        } catch (\Throwable $exception) {
            return ['code' => 400, 'msg' => '登录失败'];
        }
    }
}
